import type {GetStaticPaths, GetStaticProps, NextPage} from 'next';
import * as React from 'react'
import {useRouter} from 'next/router';
import ReactMarkdown from 'react-markdown';
import {DocsLayout, Page} from '@/components/DocsLayout';
import {getDocs, getMainReadmeFileContents, getPlatforms} from '@/utils/data';

export interface Props {
  componentPages: { name: string; components: Page[] }[],
  docsPages: Page[],
  examplePages: Page[],
  platforms: any,
  markdown: string,
}

const InnerPage: NextPage<Props> = ({
  componentPages,
  examplePages,
  docsPages,
  platforms,
  markdown,
}) => {
  const router = useRouter();
  const sidebarOpen = router.query.open === 'sidebar';

  return (
    <DocsLayout
      componentPages={componentPages}
      examplePages={examplePages}
      docsPages={docsPages}
      platforms={platforms}
      sidebarOpen={sidebarOpen}
    >
      {markdown && (
        <ReactMarkdown
          className="my-12 leading-loose"
          components={{
            ul: ({node, ordered: _ordered, ...props}) => (
              <ul
                {...props}
                className="list-disc pl-4"
              />
            ),
            li: ({node, ...props}) => (
              <li
                {...props}
                className="list-item pl-4"
              />
            ),
          }}
        >
          {markdown}
        </ReactMarkdown>
      )}
      <pre>
        <code>
          {JSON.stringify(componentPages, null, 2)}
        </code>
      </pre>
    </DocsLayout>
  )
}

export const getStaticProps: GetStaticProps = async (ctx) => {
  const { params } = ctx;
  const { url } = params as { url: string[] };
  const props = {} as Record<string, unknown>;

  const DOCS_MAPPING = {
    '/docs/philosophy': 'docs/00-philosophy.md',
  }

  const theUrl = ['', 'docs', ...url].join('/');
  const theDocFileUrl = DOCS_MAPPING[theUrl as keyof typeof DOCS_MAPPING] ?? theUrl;

  props.markdown = await getMainReadmeFileContents(theDocFileUrl) ?? null;
  props.platforms = await getPlatforms();
  props.docsPages = await getDocs({
    deriveHrefFromFilename: d => `/docs/${
      d
        .replace(/\.md/i, '')
        .split('-')
        .slice(1)
        .join('-')
    }`,
    deriveLabelFromFilename: d => (
      d
        .split('-')
        .slice(1)
        .map((dd) => dd.slice(0, 1).toUpperCase() + dd.slice(1))
        .join(' ')
        .replace(/\.md/i, '')
    ),
  });

  return {
    props,
  };
};

export default InnerPage;

export const getStaticPaths: GetStaticPaths = async () => {
  const docsPages = await getDocs({
    deriveHrefFromFilename: d => `/docs/${
      d
        .replace(/\.md/i, '')
        .split('-')
        .slice(1)
        .join('-')
    }`,
    deriveLabelFromFilename: d => (
      d
        .split('-')
        .slice(1)
        .map((dd) => dd.slice(0, 1).toUpperCase() + dd.slice(1))
        .join(' ')
        .replace(/\.md/i, '')
    ),
  });

  return {
    paths: docsPages.map((d) => d.href),
    fallback: true,
  };
};
